<template>
	<uni-popup ref="popup" type="center" @change="onChange">
		<view :style="`width:${canvasW}px;margin:130rpx auto 0 auto;`">
			<view v-if="shareData" class="radius-8 overflow-auto flex justify-center">
				<canvas id="myPoster" canvas-id="myPoster" :style="`width:${canvasW}px;height:${canvasH}px;`"></canvas>
			</view>
			<!-- <image class="w-15 h-10" style="display:none;" src="@/static/svg/direction.svg"></image> -->
			<view class="flex item-center justify-between">
				<view class="w50 mt-12 h-46 bg-primary flex center radius-8 text-white fs-16 font-normal leading-22" @click.stop="saveImage">保存海报</view>
				<button v-if="!hasWritePhotosAlbumPermission" class="w50 mt-12 h-46 flex center radius-8 text-white fs-16 font-normal leading-22" style="background:#16BE62;" @click.stop="preSaveImage">分享好友</button>
				<button v-else open-type="share" :data-share-type="dataType" :data-filePath="tempFilePath" :data-promotion-type="promotionType" class="w50 mt-12 h-46 flex center radius-8 text-white fs-16 font-normal leading-22" style="background:#16BE62;">分享好友</button>
			</view>
			<view class="mt-30 flex justify-center">
				<image class="size-40" src="@/static/svg/icon-close.svg" @click="onClose"></image>
			</view>
		</view>
	</uni-popup>
</template>

/**
 * 分享策划人主页
 */
<script setup>
	import { onShareAppMessage } from '@dcloudio/uni-app'
	import { ref, computed, watchEffect, getCurrentInstance } from 'vue'
	import { useUserStore } from '@/stores/modules/user.js'
	import { useShare } from '@/hooks/useShare.js'
	import { usePermission } from '@/hooks/usePermission.js'
	import { drawRoundImg, drawRoundImgfit, textPrewrap, drawRoundedRect, getSystem } from '@/utils/canvasUtil.js'
	
	const userStore = useUserStore()
	const { shareHomePage, shareMallPage } = useShare()
	const { hasPermission } = usePermission()
	
	const props = defineProps({
		id: {
			type: [Number, String]
		},
		show: {
			type: Boolean
		},
		dataType: {
			type: String,
			default: 'homepage'
		},
		promotionType: {
			type: String,
			default: ''
		}
	})
	
	const emits = defineEmits(['onClose'])
	
	const instance = getCurrentInstance()
	
	const popup = ref(null)
	
	const onClose = () => {
		popup.value && popup.value.close()
		emits('onClose')
	}
	
	const onChange = ({ show }) => {
		if (!show) {
			emits('onClose')
		}
	}
	
	const shareData = ref(null)
	
	const introduction = computed(() => {
		if (shareData.value && shareData.value.introduction) {
			try{
				const json = JSON.parse(shareData.value.introduction)
				return json.filter(it => it.type === 1).map(it => it.content).join('')
			} catch(e) {
				console.error(e)
				return shareData.value.introduction
			}
		}
		return ''
	})
	
	const { w, h, scale } = getSystem()
	
	const dpr = uni.getSystemInfoSync().pixelRatio	
	// 长宽比 5:4  750:600  375:300
	const canvasW = 313 * scale
	const canvasH = props.dataType === 'mall' ? 406 * scale : 518 * scale

	const draw = async () => {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		let drawY = 123 * scale
		const ctx = uni.createCanvasContext('myPoster', instance)
		let bgImg = await getImageInfo('https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/homePage-bg.png')
		drawRoundImg(ctx, bgImg.path, 0, 0, canvasW, canvasH, 0)
		
		// 头像 
		const avatar = await getImageInfo(shareData.value.logo)
		drawRoundImg(ctx, avatar.path, (canvasW - 88 * scale)/2, drawY, 88 * scale, 88 * scale, 12 * scale)
		ctx.setStrokeStyle('#fff')
		ctx.stroke()
		ctx.draw()
		
		drawY += 88 * scale + 12 * scale + 12 * scale
		// 昵称
		ctx.setFontSize(16 * scale)
		ctx.setFillStyle('#333')
		const txtW = ctx.measureText(shareData.value.businessShortName).width
		const offX = txtW >= 286 * scale ? 0 : (286 * scale - txtW)/2
		const lines = textPrewrap(ctx, shareData.value.businessShortName, 16 * scale + offX, drawY, 22 * scale, 286 * scale, 1)
		
		drawY += 22 * scale * lines + 32 * scale
		
		ctx.setFontSize(12 * scale)
		ctx.setFillStyle('#A5A5A5')
		const x1 = 20 * scale
		const x2 = 20 * scale + 69 * scale + ctx.measureText('订阅数').width * scale
		const x3 = canvasW  - 32 * scale - ctx.measureText('购买人数').width * scale
		ctx.fillText('订阅数', x1, drawY + 20 * scale)
		ctx.fillText('精品活动', x2, drawY + 20 * scale)
		ctx.fillText('购买人数', x3, drawY + 20 * scale)
		
		ctx.font = 'normal bold 14px PingFang SC,Arial,sans-serif'
		ctx.setFontSize(18 * scale)
		ctx.setFillStyle('#343434')
		ctx.fillText(shareData.value.subscribeCount, x1, drawY)
		ctx.fillText(shareData.value.activeCount, x2, drawY)
		ctx.fillText(shareData.value.buyCount, x3, drawY)
		
		ctx.setStrokeStyle('#A5A5A5')
		ctx.moveTo(canvasW/3 - 10, drawY)
		ctx.lineTo(canvasW/3 - 10, drawY + 8 * scale)
		ctx.moveTo(canvasW/3 * 2 - 10, drawY)
		ctx.lineTo(canvasW/3 * 2 - 10, drawY + 8 * scale)
		ctx.stroke()
		
		drawY += 30 * scale + 34 * scale
				
		// 小程序码
		const codeImg = await getImageInfo(shareData.value.miniImgUrl)
		drawRoundImg(ctx, codeImg.path, (canvasW - 96 * scale)/2, drawY, 96 * scale, 96 * scale, 0)
		
		if(userStore.userInfo.businessInfo && userStore.userInfo.businessInfo.posterShowAvatarState === 1){
			const avatar = await getImageInfo(userStore.userInfo.businessInfo.logo)
			drawRoundImg(ctx, avatar.path, (canvasW - 96 * scale)/2 + 26 * scale, drawY + 26 * scale, 44 * scale, 44 * scale, 22 * scale)
		}
		
		drawY += 20 * scale
		
		
		// 延迟渲染
		setTimeout(() => {
			ctx.draw(true, () => uni.hideLoading())
			preSaveImage(false)
		}, 500)
	}
	
	const draw1 = async () => {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		let drawY = 218 * scale
		const ctx = uni.createCanvasContext('myPoster', instance)
		let bgImg = await getImageInfo('https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/mallPage-bg.png')
		drawRoundImg(ctx, bgImg.path, 0, 0, canvasW, canvasH, 0)
		
		// 小程序码
		const codeImg = await getImageInfo(shareData.value.miniImgUrl)
		drawRoundImg(ctx, codeImg.path, (canvasW - 110 * scale)/2, drawY, 110 * scale, 110 * scale, 55)
		
		// 昵称
		ctx.font = 'normal bold 14px PingFang SC,Arial,sans-serif'
		ctx.setFontSize(12 * scale)
		ctx.setFillStyle('#333')
		const txtW = ctx.measureText(shareData.value.businessShortName).width
		const offX = txtW >= 286 * scale ? 0 : (286 * scale - txtW)/2
		const lines = textPrewrap(ctx, shareData.value.businessShortName, 16 * scale + offX, 360 * scale, 22 * scale, 286 * scale, 1)
		
		// 延迟渲染
		setTimeout(() => {
			ctx.draw(true, () => uni.hideLoading())
			preSaveImage(false)
		}, 500)
	}
	
	//获取图片
	const getImageInfo = (imgSrc) => {
		return new Promise((resolve, reject) => {
			uni.getImageInfo({
				src: imgSrc,
				success: (image) => {
					resolve(image);
				},
				fail: (err) => {
					reject(err);
					console.log('获取图片失败',err)
				}
			})
		})
	}

	const hasWritePhotosAlbumPermission = ref(false)
	const saveImage = async () => {
		//判断用户授权
		const res = await hasPermission('scope.writePhotosAlbum', true, '请授权添加到相册权限')
		hasWritePhotosAlbumPermission.value = res
		if (!res) {
			return
		}
		uni.canvasToTempFilePath({
			canvasId: 'myPoster',
			quality: 1,
			complete: (res) => {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success(res) {
						uni.showToast({
							title: '已保存到相册',
							icon: 'success',
							duration: 2000
						})
						setTimeout(()=>{
							onClose()
						},2000)
					}
				})
			}
		},instance);
	}
	
	onShareAppMessage((options) => {
		const shareType = options.target.dataset.shareType
		if(shareType === 'mall'){
			return {
				title: `精选超值好物好券，积分兑换享不停`,
				path: `/pagesF/merchantMall/index?id=${props.id}`,
				mageUrl: options.target.dataset.filepath
			}
		}else if (shareType === 'activity') {
			console.log("options:",options);
			const url = options.target.dataset.promotionType==='GROUP_BUY'
				?`/pagesB/activity/activity-group-buy`
				:`/pagesB/activity/activity`;
			return {
				title: options.target.dataset.title,
				path: `${url}?id=${options.target.dataset.activityId}`,
				imageUrl: options.target.dataset.filepath
			}
		} else {
			return {
				title: shareData.value.businessShortName,
				path: `/pagesA/merchant/homepage?id=${props.id}`,
				imageUrl: tempFilePath.value
			}
		}
	})
	
	watchEffect(() => {
		if (props.show && props.id) {
			if(props.dataType === 'mall'){
				shareMallPage(props.id).then(res => {
					shareData.value = res
					popup.value && popup.value.open()
					draw1()
				})
			}else{
				shareHomePage(props.id).then(res => {
					shareData.value = res
					popup.value && popup.value.open()
					draw()
				})
			}
		} else if (!props.show) {
			popup.value && popup.value.close()
		}
	})
	
	const tempFilePath = ref('')
	const preSaveImage = async (openSetting) => {
		const res = await hasPermission('scope.writePhotosAlbum', openSetting, '请授权添加到相册权限')
		hasWritePhotosAlbumPermission.value = res
		if (!res) {
			return
		}
		uni.canvasToTempFilePath({
			canvasId: 'myPoster',
			quality: 1,
			complete: (res) => {
				tempFilePath.value = res.tempFilePath
			}
		}, instance)
	}
</script>
